package com.wstuo.itsm.bean;

import java.util.Date;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.log4j.Logger;

/**
 * 使用工具类
 * org.apache.commons.beanutils.BeanUtils
 * 定义相关转换器
 * @author gs60
 *
 */
public class BeanUtil implements IBeanUtil{
	
	final static Logger LOGGER = Logger.getLogger(BeanUtil.class);
	
	public BeanUtil() {
	}

	public BeanUtil(Converter integerConvert, Converter dateConvert,
			Converter mapConverter) {
		this.integerConvert = integerConvert;
		this.dateConvert = dateConvert;
		this.mapConverter = mapConverter;
		//---------------注册转换器----------------//
		if( dateConvert != null ){
    		ConvertUtils.register(dateConvert , Date.class);
		}
		/*if( mapConverter != null ){
			ConvertUtils.register(mapConverter , Map.class);
		}*/
		if( integerConvert != null){
			ConvertUtils.register(integerConvert , Integer.class);
		}
	}


	/**
	 * Map转换成具体的bean
	 */
	public void populate(final Object object,final Map<String,Object> lineData){
		if( object == null || lineData == null || lineData.size() == 0){
			return;
		}
    	try {
    		replaceMapKey(lineData, "statusId", "statusName");
    		replaceMapKey(lineData, "systemPlatformId", "systemPlatformName");
    		replaceMapKey(lineData, "brandId", "brandName");
    		replaceMapKey(lineData, "providerId", "providerName");
    		replaceMapKey(lineData, "locId", "locationName");
    		//使用此工具是，保证键值的值不会是空白字符串；
    		BeanUtils.populate(object, lineData);
    		//ConvertUtils.deregister();//注销全部的转换器
		} catch (Exception e) {
        	LOGGER.error( e );
		}
	}

	/**
	 * 更换map中的key；例如自定义表单中：statusId 实际上对应key应该是status；所以进行一个替换；
	 * @param lineData
	 * @param oldKey
	 * @param newKey
	 */
	private void replaceMapKey(final Map<String,Object> lineData,String oldKey,String newKey){
		Object value = lineData.get(oldKey);
		if( value != null){
			lineData.remove(oldKey);
			lineData.put(newKey, value);
		}
	}
	
	/**
	 * Integer转换器
	 */
	private Converter integerConvert;
	/**
	 * 日期的转换器
	 */
	private Converter dateConvert;
	/**
	 * Map转换器
	 */
	private Converter mapConverter;
	
	public Converter getIntegerConvert() {
		return integerConvert;
	}

	public void setIntegerConvert(Converter integerConvert) {
		this.integerConvert = integerConvert;
	}

	public Converter getDateConvert() {
		return dateConvert;
	}

	public void setDateConvert(Converter dateConvert) {
		this.dateConvert = dateConvert;
	}

	public Converter getMapConverter() {
		return mapConverter;
	}

	public void setMapConverter(Converter mapConverter) {
		this.mapConverter = mapConverter;
	}
}
